<?php


namespace app\controller\admin;


use app\BaseController;
use think\facade\Db;
use think\Request;

class MenuController extends BaseController
{
    /**
     * 侧边栏菜单权限
     * @return \think\response\Json
     */
    public function getUserMenuList()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $roleId = $userInfo->role_id;
            $list = DB::name('admin_menu')
                ->alias('m')
                ->join('admin_rule r', 'm.id = r.menu_id', 'left')
                ->where('r.is_del', '=', 0)
                ->where('r.role_id', '=', $roleId)
                ->where('m.is_del', '=', 0)
                ->field('m.*,r.role_id')
                ->order('m.sort')
                ->select()
                ->toArray();
            return $this->success(format_menu($list));
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 角色分配权限
     * @return \think\response\Json
     */
    public function getRoleMenuList()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $roleId = $userInfo->role_id;
            $list = DB::name('admin_menu')
                ->alias('m')
                ->join('admin_rule r', 'm.id = r.menu_id', 'left')
                ->where('r.is_del', '=', 0)
                ->where('r.role_id', '=', $roleId)
                ->where('m.is_del', '=', 0)
                ->field('m.*,r.role_id')
                ->order('m.sort')
                ->select()
                ->toArray();
            return $this->success(format_menu($list));
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 添加 修改菜单
     * @param Request $request
     * @return \think\response\Json
     */
    public function saveMenuInfo(Request $request)
    {
        try {
            DB::startTrans();
            $userInfo = $request->userInfo;
            $roleId = $userInfo->role_id;
            $params = $request->only(['type', 'pid', 'is_del', 'path', 'title', 'name', 'component',
                'icon', 'sort', 'is_hide_bread', 'is_hide_menu']);
            if (!$request->param('type')) {
                throw new \Exception('权限类型不能为空');
            }
            if (!$request->param('component')) {
                throw new \Exception("组件地址不能够为空");
            }
            $params['icon'] = $params['icon'] ?: 'md-reorder';
            $menuId = $request->param('id');
            if (!$menuId) {
                $menuId = DB::name('admin_menu')->insertGetId($params);
                DB::name('admin_rule')->insert(['menu_id' => $menuId, 'role_id' => $roleId]);
            } else {
                DB::name('admin_menu')->where('id', $menuId)->update($params);
                $ruleInfo = DB::name('admin_rule')->where(['menu_id' => $menuId, 'role_id' => $roleId])->find();
                if ($ruleInfo && $ruleInfo['is_del'] != $params['is_del']) {
                    DB::name('admin_rule')->where('id', $ruleInfo['id'])->update(['is_del' => $params['is_del']]);
                }
            }
            DB::commit();
            return $this->success();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception);
        }
    }

    /**
     * 菜单列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getMenuList(Request $request)
    {
        $list = DB::name('admin_menu')->select()->toArray();
        $menuList = [];
        foreach ($list as $item) {
            $data = [
                'name' => $item['name'],
                'id' => $item['id'],
                'pid' => $item['pid'],
                'title' => $item['title'],
                'icon' => $item['icon'],
                "is_hide_menu" => $item['is_hide_menu'],
                'is_del' => $item['is_del'],
                "type" => $item['type'],
                'sort' => $item['sort']
            ];
            array_push($menuList, $data);
        }
        $tree = list_to_tree($menuList, 'id', 'pid', 'children');
        return $this->success($tree);
    }

    /**
     * 角色权限列表
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getRuleMenuList(Request $request)
    {
        $roleId = $request->param('role_id');
        $list = DB::name('admin_menu')
            ->alias('m')
            ->join('admin_rule r', 'm.id = r.menu_id')
            ->where('r.is_del', '=', 0)
            ->where('r.role_id', '=', $roleId)
            ->where('m.is_del', '=', 0)
            ->field('m.*,r.role_id')
            ->order('m.sort')
            ->select()
            ->toArray();
        $menuList = [];
        foreach ($list as $item) {
            $data = [
                'name' => $item['name'],
                'id' => $item['id'],
                'pid' => $item['pid'],
                'title' => $item['title'],
                'icon' => $item['icon'],
                "is_hide_menu" => $item['is_hide_menu'],
                'is_del' => $item['is_del'],
                "type" => $item['type'],
                'sort' => $item['sort']
            ];
            array_push($menuList, $data);
        }
        $tree = list_to_tree($menuList, 'id', 'pid', 'children');
        return $this->success($tree);
    }

    /**
     * 获取菜单详情
     * @param Request $request
     * @return mixed
     */
    public function getMenuInfo(Request $request)
    {
        try {
            $id = $request->param('id');
            if (!$id) {
                throw new \Exception('缺少参数');
            }
            $info = DB::name('admin_menu')->where('id', $id)->find();
            if ($info['pid'] > 0) {
                $parentInfo = DB::name('admin_menu')->where('id', $info['pid'])->find();
                $parentTitle = $parentInfo['title'];
            } else {
                $parentTitle = '顶级菜单';
            }
            $info['titleTop'] = $parentTitle;
            return $this->success($info);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 设置规则
     * @param Request $request
     * @return mixed
     */
    public function editRule(Request $request)
    {
        try {
            DB::startTrans();
            $newIds = $request->param('newIds');
            $oldIds = $request->param('oldIds');
            $roleId = $request->param('roleId');
            sort($newIds);
            sort($oldIds);

            // 要新增的ids
            $addIds = array_diff($newIds, $oldIds);
            // 要删除的ids
            $delIds = array_diff($oldIds, $newIds);
//            dd($addIds, $delIds);
            // 删除要删除的
            if ($delIds) {
                DB::name('admin_rule')
                    ->where('role_id', $roleId)
                    ->whereIn('menu_id', $delIds)
                    ->update(['is_del' => 1, 'update_time' => date('Y-m-d H:i:s')]);
            }

            // 添加要添加的
            if ($addIds) {
                foreach ($addIds as $k => $menuId) {
                    $info = DB::name('admin_rule')->where('menu_id', $menuId)->where('role_id', $roleId)->find();
                    if ($info) {
                        DB::name('admin_rule')->where('id', $info['id'])->update([
                            'is_del' => 0,
                            'update_time' => date('Y-m-d H:i:s')
                        ]);
                    } else {
                        DB::name('admin_rule')->insert([
                            'menu_id' => $menuId,
                            'role_id' => $roleId,
                            'create_time' => date('Y-m-d H:i:s'),
                            'update_time' => date('Y-m-d H:i:s'),
                        ]);
                    }
                }
            }
            DB::commit();
            return $this->success();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception);
        }
    }
}